<?php

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Aliyun
{
    // seiven2
    // LTAI4GJiiaww3WyLq5KKph9p
    // PQKbfUrWRIPgk25Dn2xaFS64CwiAsJ
    private static $accessKeyId = 'LTAI4FyXhXvQTWG7dkvjcP14';
    private static $accessSecret = '4hTDmQGbvfFEmMAIuVi4j32LABaIws';
    // 地区
    public static $Region = [
        'cn-zhangjiakou' => 'ecs.cn-zhangjiakou.aliyuncs.com'
    ];
    public static $config;
    private $RegionId;
    private $Host;

    function __construct($RegionId, $accessKeyId = null, $accessSecret = null)
    {
        $this->RegionId = $RegionId;
        AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)
            ->regionId($this->RegionId)
            ->asDefaultClient();
    }

    static function getConfig($product)
    {
        return \AlibabaCloud\Client\Config\Config::get('endpoints.' . $product);
    }

    function setHost($product = 'ecs')
    {
        $config = self::getConfig($product);
        $this->Host = $config[$this->RegionId];
    }

    /**
     * 获取域名列表
     * @return array
     */
    function DescribeDomains()
    {
        $data = [
            'RegionId' => $this->RegionId,
            'PageNumber' => 1,
            'PageSize' => 100,
        ];
        return $this->request('Alidns', __FUNCTION__, $data, '2015-01-09');
    }

    /**
     * 获取域名详情
     * @param $DomainName 域名
     * @return array
     */
    function DescribeDomainInfo($DomainName)
    {
        $data = [
            'RegionId' => $this->RegionId,
            'DomainName' => $DomainName,
        ];
        return $this->request('Alidns', __FUNCTION__, $data, '2015-01-09');
    }

    /**
     * 获取域名解析记录
     * @param $DomainName 域名
     * @param $PageSize
     * @param $PageNumber
     * @return array
     */
    function DescribeDomainRecords($DomainName, $PageNumber, $PageSize)
    {
        $data = [
            'RegionId' => $this->RegionId,
            'DomainName' => $DomainName,
            'PageNumber' => $PageNumber,
            'PageSize' => $PageSize,
        ];
        return $this->request('Alidns', __FUNCTION__, $data, '2015-01-09');
    }

    /**
     * 批量管理域名解析
     * @param $Type 域名
     * @param $DomainRecordInfo 具体操作信息
     * @return array
     */
    function OperateBatchDomain($Type, $DomainRecordInfo)
    {
        $data = array_merge([
            'RegionId' => $this->RegionId,
            'Type' => $Type,
        ], $DomainRecordInfo);
        return $this->request('Alidns', __FUNCTION__, $data, '2015-01-09');
    }

    /**
     * 删除域名解析
     * @param $RecordId
     * @return array
     */
    function DeleteDomainRecord($RecordId)
    {
        $data = [
            'RegionId' => $this->RegionId,
            'RecordId' => $RecordId,
        ];
        return $this->request('Alidns', __FUNCTION__, $data, '2015-01-09');
    }

    /**
     * 查询余额
     * @return array
     */
    function QueryAccountBalance()
    {
        $data = [
            'RegionId' => $this->RegionId,
        ];
        return $this->request('BssOpenApi', __FUNCTION__, $data, '2017-12-14');
    }

    /**
     * 创建实例
     * @param $ImageId
     * @param $InstanceType
     * @param $SecurityGroupId
     * @param null $InstanceName
     * @param string $InternetChargeType 带宽计价方式
     * @param string $InstanceChargeType 实例计价方式
     * @param bool $AutoRenew
     * @return array
     */
    function CreateInstance($ImageId, $InstanceType, $SecurityGroupId, $InstanceName = null, $InternetChargeType = 'PayByTraffic', $InstanceChargeType = 'PostPaid', $AutoRenew = true)
    {
        if (is_null($InstanceName)) $InstanceName = 'dun_' . rand(1, 99999);
        $data = [
            'RegionId' => $this->RegionId,
            'InstanceType' => $InstanceType,
            'ImageId' => $ImageId,
            'SecurityGroupId' => $SecurityGroupId,
            'InstanceName' => $InstanceName,
            'InternetChargeType' => $InternetChargeType,
            'InstanceChargeType' => $InstanceChargeType,
            'Period' => 1,
            'PeriodUnit' => 'Month',
            'AutoRenew' => $AutoRenew,
            'AutoRenewPeriod' => 1,
            'HostName' => $InstanceName,
            'Password' => Helper::hash_orderid(Helper::hash_orderid(time())),
        ];
        return $this->request('Ecs', __FUNCTION__, $data);
    }

    /**
     *
     * @param $SecurityGroupId 安全组
     * @param $InstanceChargeType 实例的计费方式。取值范围：
     * PostPaid：按量付费
     * PrePaid：包年包月
     * @param $InternetChargeType  公网带宽计费方式。取值范围：
     * PayByBandwidth：按固定带宽计费。
     * PayByTraffic：按使用流量计费。
     * @param $Status
     *
     * Pending：创建中
     * Running：运行中
     * Starting：启动中
     * Stopping：停止中
     * Stopped：已停止
     * @param $PageNumber
     * @param $PageSize
     * @return array
     */
    function DescribeInstances($SecurityGroupId = null, $InstanceChargeType = null, $PageNumber = 1, $PageSize = 100)
    {
        $data = [
            'PageNumber' => $PageNumber,
            'PageSize' => $PageSize,
        ];
        if ($SecurityGroupId) $data['SecurityGroupId'] = $SecurityGroupId;
        if ($InstanceChargeType) $data['InstanceChargeType'] = $InstanceChargeType;
        return $this->request('Ecs', __FUNCTION__, $data);
    }

    /**
     * 创建安全组
     * @return array
     */
    function CreateSecurityGroup()
    {
        $data = [
            'RegionId' => $this->RegionId,
        ];
        return $this->request('Ecs', __FUNCTION__, $data);
    }

    /**
     * @param $InstanceId
     * @param string $ImageName
     * @param string $Description
     * @return array
     */
    function CreateImage($InstanceId, $ImageName = '', $Description = '')
    {
        $data = [
            'RegionId' => $this->RegionId,
            'InstanceId' => $InstanceId
        ];
        return $this->request('Ecs', __FUNCTION__, $data);
    }

    /**
     * @param string $ImageOwnerAlias system,self,others,marketplace
     * @param int $PageNumber
     * @param int $PageSize
     * @return array
     */
    function DescribeImages($ImageOwnerAlias = 'self', $PageNumber = 1, $PageSize = 50)
    {
        $data = [
            'RegionId' => $this->RegionId,
            'ImageOwnerAlias' => $ImageOwnerAlias,
            'PageNumber' => $PageNumber,
            'PageSize' => $PageSize,
        ];
        return $this->request('Ecs', __FUNCTION__, $data);
    }

    /**
     * 阿里云请求
     * @param string $product
     * @param $action
     * @param $data
     * @param $version
     * @return array
     */
    private function request($product = 'Ecs', $action, $data, $version = '2014-05-26')
    {
        try {
            $result = AlibabaCloud::rpc()
                ->product($product)
                ->scheme('https')// https | http
                ->version($version)
                ->action($action)
                ->method('POST')
                ->host($this->Host)
                ->options([
                    'query' => $data,
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            Logger::getInterface(strtolower(__CLASS__ . '/' . $action))->error($e->getMessage());
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            Logger::getInterface(strtolower(__CLASS__ . '/' . $action))->error($e->getMessage());
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

}
